package me.eddiechow.interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 线程通信 这里使用的 Lock + Condition 来控制实现，还可以使用 阻塞队列来实现
 * @author: zhoudi
 * @date: 2017/6/12 22:34
 */
public class ThreadCommunicationTest {

    public static void main(String[] args) {
        // 线程1 10次 线程2 10次 线程1 10次 线程2 10次。。。循环50次
        final Business business = new Business();
        new Thread(){
            @Override
            public void run() {
                // 线程1
                for (int i = 0; i < 50; i++) {
                    business.thread1(i);
                }
            }
        }.start();

        //线程2
        for (int i = 0; i < 50; i++) {
            business.thread2(i);
        }

    }

    private static class Business {
        private Lock lock = new ReentrantLock();
        private Condition condition = lock.newCondition();
        private boolean isThread1 = true;
        public void thread1(int i){
            lock.lock();
            try {
                while (!isThread1) {
                    condition.await();
                }
                for (int j = 0; j < 10; j++) {
                    try {
                        Thread.sleep((long)(Math.random()*1500));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread1 sequence of " + j + " main loop of "+i);
                }
                isThread1 = false;
                condition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void thread2(int i){
            lock.lock();
            try {
                while (isThread1) {
                    condition.await();
                }
                for (int j = 0; j < 10; j++) {
                    try {
                        Thread.sleep((long)(Math.random()*1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread2 sequence of " + j + " main loop of "+i);
                }
                isThread1 = true;
                condition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
